'use client'
import { Button } from '@/components/ui/button'
import { useToast } from '@/hooks/use-toast'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import ExtensionIcon from '@/assets/icons/extension.svg'
import ContinuationIcon from '@/assets/icons/continuation.svg'
import RegenrateIcon from '@/assets/icons/regenrate.svg'
import RewriteIcon from '@/assets/icons/rewrite.svg'
import StreamlineIcon from '@/assets/icons/streamline.svg'
import CopyIcon from '@/assets/icons/copy.svg'
import UndoIcon from '@/assets/icons/undo.svg'
import RedoIcon from '@/assets/icons/redo.svg'
import { useState, useRef, useMemo, useEffect, FC, PropsWithChildren } from 'react'
import { TextHistoryDialog } from './TextHistoryDialog'
import { videoService, commonService } from '@/services'
import { useVideoStore } from '@/stores/video'
import { useGraphicStore } from '@/stores/audio'
import { cn } from '@/lib/utils'
import TranslateIcon from '@/assets/icons/translate.svg'
import {
  TooltipProvider,
  Tooltip,
  TooltipTrigger,
  TooltipContent,
} from '@/components/ui/tooltip'

interface HistoryState {
  text: string
  selectionStart: number
  selectionEnd: number
  timestamp: number
}

const maxTextLength = 1000 // 最大文案长度

interface ToolsIconProps extends PropsWithChildren {
  icon: string
  onClick: () => void
}

const toolIcons = [
  {
    icon: ExtensionIcon,
    label: 'Extension',
    key: 'expand',
  },
  {
    icon: RewriteIcon,
    label: 'Rewrite',
    key: 'modify',
  },
  {
    icon: ContinuationIcon,
    label: 'Continuation',
    key: 'continue',
  },
  {
    icon: StreamlineIcon,
    label: 'Streamline',
    key: 'simplify',
  },
  {
    icon: UndoIcon,
    label: 'Undo',
    key: 'undo',
  },
  {
    icon: RedoIcon,
    label: 'Redo',
    key: 'redo',
  },
  {
    icon: RegenrateIcon,
    label: 'Regenrate',
    key: 'regenrate',
  },
  {
    icon: CopyIcon,
    label: 'Copy',
    key: 'copy',
  },
]

export function TextSection({
  className,
  defText,
  createdId,
  commit,
  getFormInfo,
  setFormSectionParams,
  inGraphic = false, // 是否在图文创作中
}: {
  className?: string
  createdId: string
  commit: (value: string) => void
  getFormInfo?: () => {
    face_image_url: string // 面部图像
    video_url: string // 原始视频
    vol: string | number
    speed: string
    tone_id: string
  }
  setFormSectionParams: (v: any) => void
  defText?: string
  inGraphic?: boolean
}) {
  const [textValue, setTextValue] = useState('')
  const [translatedValue, setTranslatedText] = useState({
    sourceText: '',
    translatedText: '',
  })
  const [selectedTextLength, setSelectedTextLength] = useState(0)

  // const { resText: textValue, setResText: setTextValue } = useVideoStore()
  const { getBroadcastDetail, getAudioVideoDetail } = useVideoStore()
  const { getGraphicTextDetail } = useGraphicStore()
  const [captionValue, setCaptionValue] = useState<string>('')

  // 历史记录相关状态
  const [history, setHistory] = useState<HistoryState[]>([
    {
      text: textValue,
      selectionStart: 0,
      selectionEnd: textValue.length,
      timestamp: Date.now(),
    },
  ])
  const [currentHistoryIndex, setCurrentHistoryIndex] = useState(0)
  const [isHistoryDialogOpen, setIsHistoryDialogOpen] = useState(false)
  const textareaRef = useRef<HTMLTextAreaElement>(null)

  useEffect(() => {
    if (!inGraphic && createdId) {
      getBroadcastDetail(createdId).then((text) => {
        // console.log('getBroadcastDetail text', text)
        setTextValue(text)
      })
    }
  }, [inGraphic, createdId, getBroadcastDetail])

  useEffect(() => {
    if (inGraphic && createdId && defText) {
      setTextValue(defText)
    }
  }, [inGraphic, createdId, defText])

  // 添加历史记录
  const addToHistory = (
    newText: string,
    selectionStart: number,
    selectionEnd: number,
  ) => {
    const newHistory = history.slice(0, currentHistoryIndex + 1)
    newHistory.push({
      text: newText,
      selectionStart,
      selectionEnd,
      timestamp: Date.now(),
    })

    setHistory(newHistory)
    setCurrentHistoryIndex(newHistory.length - 1)
  }

  // 从历史记录中恢复文本
  const handleSelectHistory = (item: any) => {
    const updatedText = item.result.data ?? ''
    setTextValue(updatedText)
    addToHistory(updatedText, 0, updatedText.length)

    setIsHistoryDialogOpen(false)
    setFormSectionParams(item)
    toast({
      description: '已恢复到历史版本',
      duration: 2000,
    })
  }

  // 处理文本变化
  const handleChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
    setTextValue(event.target.value)
  }

  const handleSelect = () => {
    const textarea = textareaRef.current
    if (textarea) {
      const selectedText = textarea.value.substring(
        textarea.selectionStart,
        textarea.selectionEnd,
      )
      setSelectedTextLength(selectedText.length)
    }
  }

  // 获取选中的文本
  const getSelectedText = (): { text: string; start: number; end: number } => {
    const textArea = textareaRef.current
    if (!textArea) return { text: '', start: 0, end: 0 }

    const start = textArea.selectionStart
    const end = textArea.selectionEnd
    return {
      text: textValue.substring(start, end),
      start,
      end,
    }
  }

  // 替换文本并设置选中范围
  const replaceText = (newText: string, start: number, end: number) => {
    const before = textValue.substring(0, start)
    const after = textValue.substring(end)
    const updatedText = before + newText + after

    // 计算新的选择范围
    const newSelectionStart = start
    const newSelectionEnd = start + newText.length

    setTextValue(updatedText)
    addToHistory(updatedText, newSelectionStart, newSelectionEnd)

    // 设置新的选择范围
    setTimeout(() => {
      if (textareaRef.current) {
        textareaRef.current.focus()
        textareaRef.current.selectionStart = newSelectionStart
        textareaRef.current.selectionEnd = newSelectionEnd
      }
    }, 100)
  }

  // 扩写、改写、续写处理
  const handleTextOperation = async (
    type: 'expand' | 'modify' | 'continue' | 'simplify',
  ) => {
    const editResultType = {
      expand: '扩写',
      modify: '改写',
      continue: '续写',
      simplify: '精简',
    }
    const { text, start, end } = getSelectedText()
    if (!text && type !== 'simplify') {
      toast({
        variant: 'destructive',
        description: '请先选择需要修改的文本',
        duration: 2000,
      })
      return
    }
    const selectType = editResultType[type]
    const editApi = inGraphic
      ? videoService.editGraphicResult
      : videoService.editResult
    const response = await editApi({
      id: +createdId,
      type: selectType,
      select_content: text,
      original_content: textValue,
    })
    // 判断文字前后是否被修改了
    const newText = response.result.data
    const beforeText = textValue.substring(0, start)
    const afterText = textValue.substring(end)

    if (newText.indexOf(beforeText) > -1 && newText.indexOf(afterText) > -1) {
      // 部分替换
      console.log('🚀 ~ handleTextOperation ~ 部分替换 response:', response)
      const changeText = newText.substring(start, newText.length - afterText.length)
      replaceText(changeText, start, end)
    } else {
      // 需要全部替换
      console.log('🚀 ~ handleTextOperation ~ response 需要全部替换:', response)
      replaceText(newText, 0, textValue.length)
    }
  }

  // 撤销
  const handleUndo = () => {
    if (currentHistoryIndex > 0) {
      const prevState = history[currentHistoryIndex - 1]
      setTextValue(prevState.text)
      setCurrentHistoryIndex(currentHistoryIndex - 1)

      setTimeout(() => {
        const textArea = textareaRef.current
        if (textArea) {
          textArea.focus()
          textArea.selectionStart = prevState.selectionStart
          textArea.selectionEnd = prevState.selectionEnd
        }
      }, 0)
    }
  }

  // 重做
  const handleRedo = () => {
    if (currentHistoryIndex < history.length - 1) {
      const nextState = history[currentHistoryIndex + 1]
      setTextValue(nextState.text)
      setCurrentHistoryIndex(currentHistoryIndex + 1)

      setTimeout(() => {
        const textArea = textareaRef.current
        if (textArea) {
          textArea.focus()
          textArea.selectionStart = nextState.selectionStart
          textArea.selectionEnd = nextState.selectionEnd
        }
      }, 0)
    }
  }

  // 重新生成文案任务
  const handleRegenerate = async () => {
    let newText: string = ''
    if (inGraphic) {
      newText = await getGraphicTextDetail(createdId).then((text) => {
        console.log('handleRegenerate getGraphicTextDetail text', text)
        return text
      })
    } else {
      newText = await getBroadcastDetail(createdId, true).then((text) => {
        console.log('handleRegenerate getBroadcastDetail text', text)
        return text as string
      })
    }

    setTextValue(newText)

    // 全文操作后，选中整个文本
    const newSelectionStart = 0
    const newSelectionEnd = newText.length

    addToHistory(newText, newSelectionStart, newSelectionEnd)

    setTimeout(() => {
      if (textareaRef.current) {
        textareaRef.current.focus()
        textareaRef.current.selectionStart = newSelectionStart
        textareaRef.current.selectionEnd = newSelectionEnd
      }
    }, 0)
  }

  // 复制到剪贴板
  const { toast } = useToast()

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(textValue)
      toast({
        description: '文本已复制到剪贴板',
        duration: 2000,
      })
    } catch (err) {
      console.error('Failed to copy text: ', err)
      toast({
        variant: 'destructive',
        description: '复制失败',
        duration: 2000,
      })
    }
  }
  const showSouceText = () => {
    setTextValue(translatedValue.sourceText)
    setTranslatedText({
      sourceText: '',
      translatedText: '',
    })
  }
  // 翻译
  const handleTranslate = async () => {
    const responseText = await commonService.translate(textValue, '中文')
    console.log('🚀 ~ handleTranslate ~ responseText:', responseText)
    setTranslatedText({
      sourceText: textValue,
      translatedText: responseText,
    })
    const newText = responseText
    setTextValue(newText)

    // 全文操作后，选中整个文本
    const newSelectionStart = 0
    const newSelectionEnd = newText.length

    addToHistory(newText, newSelectionStart, newSelectionEnd)

    setTimeout(() => {
      if (textareaRef.current) {
        textareaRef.current.focus()
        textareaRef.current.selectionStart = newSelectionStart
        textareaRef.current.selectionEnd = newSelectionEnd
      }
    }, 0)
  }

  const isDisabledControl = useMemo(() => {
    return !createdId
  }, [createdId])

  const handleCreateVideo = async () => {
    if (!createdId) {
      toast({
        variant: 'destructive',
        description: '请先生成文案',
        duration: 2000,
      })
      return
    }
    if (captionValue === '') {
      toast({
        variant: 'destructive',
        description: '请选择是否生成字幕',
        duration: 2000,
      })
      return
    }
    const formInfo = getFormInfo!()
    if (!formInfo.video_url) {
      toast({
        variant: 'destructive',
        description: '请上传原始视频',
        duration: 2000,
      })
      return
    }
    if (!formInfo.tone_id) {
      toast({
        variant: 'destructive',
        description: '请选择生成声音',
        duration: 2000,
      })
      return
    }
    // 生成口播视频
    await videoService.updateEditText({
      id: createdId,
      content: textValue, // 文案内容
      face_image_url: formInfo.face_image_url, // 面部图像
      video_url: formInfo.video_url, // 原始视频
      vol: formInfo.vol,
      speed: formInfo.speed,
      tone_id: formInfo.tone_id,
    })
    const resultId = await videoService
      .videoCreationAudioVideo({
        broadcast_copy_history_id: Number(createdId),
        build_caption: captionValue === '1' ? 1 : 0,
      })
      .then((res) => {
        // 轮询获取状态~
        console.log('videoCreationAudioVideo res', res)
        // const resultId = res.audioVideo.id
        return res.audioVideo.id
      })
    console.log('resultId:', resultId)
    getAudioVideoDetail(resultId).then((videoUrl: string) => {
      console.log('获取到结果了 videoUrl:', videoUrl)
      commit(videoUrl) // 触发commit
    })
  }

  const handleSaveText = () => {
    if (!textValue) {
      toast({
        variant: 'destructive',
        description: '文案内容不能为空',
        duration: 2000,
      })
      return
    }
    videoService
      .generateGraphicValue({
        id: createdId,
        content: textValue, // 文案内容
      })
      .then((res) => {
        console.log('res', res)
        toast({
          description: '文案保存成功',
          duration: 2000,
        })
        if (history[history.length - 1].text !== textValue) {
          addToHistory(textValue, 0, textValue.length)
        }
      })
  }

  return (
    <div className={cn('flex flex-1 flex-col ', className)}>
      <div className=" bg-white/10 p-4 rounded-lg border border-[#B9AEFF]/10">
        <div className="text-white/80 flex items-center justify-between pb-3">
          <span>Edit</span>
          <TooltipProvider>
            <Tooltip>
              <TooltipTrigger asChild>
                <TranslateIcon
                  onClick={isDisabledControl ? undefined : handleTranslate}
                  className={cn(
                    'w-4 h-4',
                    isDisabledControl && 'opacity-50 cursor-not-allowed',
                  )}
                />
              </TooltipTrigger>
              <TooltipContent>Translate</TooltipContent>
            </Tooltip>
          </TooltipProvider>
        </div>
        {/* 顶部按钮 */}
        {/* <div className="flex justify-between pb-4">
          <div className="flex gap-2">
            <Button variant="outline" size="sm">
              新创作的
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => setIsHistoryDialogOpen(true)}
            >
              历史记录
            </Button>
          </div>
        </div> */}

        {/* 中间内容区域 */}
        <div className="flex flex-col flex-1">
          {/* 编辑工具栏 */}
          {/* <div className="flex select-none px-4 py-1 items-center gap-3 flex-wrap border-b">
            <Button
              variant="ghost"
              size="sm"
              className="px-2 h-8"
              onClick={() => handleTextOperation('expand')}
              disabled={isDisabledControl}
            >
              扩写
            </Button>
            <Button
              variant="ghost"
              size="sm"
              className="px-2 h-8"
              onClick={() => handleTextOperation('modify')}
              disabled={isDisabledControl}
            >
              改写
            </Button>
            <Button
              variant="ghost"
              size="sm"
              className="px-2 h-8"
              onClick={() => handleTextOperation('continue')}
              disabled={isDisabledControl}
            >
              续写
            </Button>
            <Button
              variant="ghost"
              size="sm"
              className="px-2 h-8"
              onClick={() => handleTextOperation('simplify')}
              disabled={isDisabledControl}
            >
              精简
            </Button>
            <Button
              variant="ghost"
              size="sm"
              className="px-2 h-8"
              onClick={handleUndo}
              disabled={isDisabledControl || currentHistoryIndex <= 0}
            >
              <UndoIcon width="20" height="20" />
            </Button>
            <Button
              variant="ghost"
              size="sm"
              className="px-2 h-8"
              onClick={handleRedo}
              disabled={
                isDisabledControl || currentHistoryIndex >= history.length - 1
              }
            >
              <RedoIcon width="20" height="20" />
            </Button>
            <Button
              variant="ghost"
              size="sm"
              className="px-2 h-8"
              onClick={handleRegenerate}
              disabled={isDisabledControl}
            >
              重新生成
            </Button>
            <Button
              variant="ghost"
              size="sm"
              className="px-2 h-8"
              onClick={handleCopy}
              disabled={isDisabledControl}
            >
              复制
            </Button>
          </div> */}

          {/* 文本内容 */}
          <div className="flex-1">
            <div className="h-full text-sm leading-relaxed">
              <Textarea
                ref={textareaRef}
                className="w-full h-[138px] bg-black/40 text-white/80 placeholder:text-white/40 text-sm my-scrollbar resize-none border border-transparent focus:border-white"
                placeholder="Type your message here."
                value={textValue}
                onChange={handleChange}
                onSelect={handleSelect}
                disabled={isDisabledControl}
              />
            </div>
            <div className="flex items-center justify-between pt-2.5">
              {toolIcons.map((item) => {
                return (
                  <TooltipProvider key={item.key}>
                    <Tooltip>
                      <TooltipTrigger asChild>
                        <span
                          className={cn(
                            'cursor-pointer',
                            !isDisabledControl && 'hover:text-[#AEA0FF]',
                            isDisabledControl && 'opacity-50',
                          )}
                          onClick={() => {
                            if (isDisabledControl) return
                            if (item.key === 'expand') {
                              handleTextOperation('expand')
                            }
                            if (item.key === 'modify') {
                              handleTextOperation('modify')
                            }
                            if (item.key === 'continue') {
                              handleTextOperation('continue')
                            }
                            if (item.key === 'simplify') {
                              handleTextOperation('simplify')
                            }
                            if (item.key === 'undo') {
                              handleUndo()
                            }
                            if (item.key === 'redo') {
                              handleRedo()
                            }
                            if (item.key === 'regenrate') {
                              handleRegenerate()
                            }
                            if (item.key === 'copy') {
                              handleCopy()
                            }
                          }}
                        >
                          <item.icon className="w-5 h-5" />
                        </span>
                      </TooltipTrigger>
                      <TooltipContent>{item.label}</TooltipContent>
                    </Tooltip>
                  </TooltipProvider>
                )
              })}
            </div>
          </div>

          {/* 底部字数统计和翻译按钮 */}
          <div className="flex sr-only px-4 pb-4 justify-between text-xs items-center t-5">
            <div className="text-right text-sm text-gray-400">
              {selectedTextLength}/{textValue.length}字
            </div>
            {textValue.length > maxTextLength && (
              <div className="flex items-center text-red-500 gap-2">
                文案不能超过{maxTextLength}字
              </div>
            )}
            <div className="flex gap-2">
              {translatedValue.sourceText && (
                <Button
                  size="sm"
                  variant="outline"
                  onClick={showSouceText}
                  disabled={isDisabledControl}
                >
                  显示原文
                </Button>
              )}
              <Button
                variant={translatedValue.sourceText ? 'default' : 'outline'}
                size="sm"
                onClick={handleTranslate}
                disabled={isDisabledControl}
              >
                翻&nbsp;译
              </Button>
            </div>
          </div>
        </div>
      </div>
      {/* 底部选项 */}
      {!inGraphic ? (
        <div className="my-5 flex justify-between gap-x-2">
          <div className="flex flex-1 justify-center whitespace-nowrap gap-2 items-center text-base">
            Generate Caption:
            <RadioGroup
              disabled={isDisabledControl}
              className="flex gap-2"
              defaultValue=""
              value={captionValue}
              onValueChange={(val) => {
                setCaptionValue(val)
              }}
            >
              <div className="flex items-center cursor-pointer space-x-2">
                <RadioGroupItem value="1" id="r1" />
                <Label htmlFor="r1">Yes</Label>
              </div>
              <div className="flex items-center cursor-pointer space-x-2">
                <RadioGroupItem value="0" id="r2" />
                <Label htmlFor="r2">No</Label>
              </div>
            </RadioGroup>
          </div>
          <Button
            disabled={isDisabledControl || textValue.length > maxTextLength}
            onClick={handleCreateVideo}
            className="h-11 rounded-full disabled:bg-white/10 disabled:text-white/40"
          >
            Click to Generate Oral Video
          </Button>
        </div>
      ) : (
        <div className="flex pt-10 px-4">
          {/* <div></div> */}
          <Button
            className="w-full h-11 rounded-full disabled:bg-white/10 disabled:text-white/40"
            disabled={isDisabledControl || textValue.length > maxTextLength}
            onClick={handleSaveText}
          >
            Save
          </Button>
        </div>
      )}

      {/* 历史记录对话框 */}
      <TextHistoryDialog
        inGraphic={inGraphic}
        open={isHistoryDialogOpen}
        onOpenChange={setIsHistoryDialogOpen}
        onSelectHistory={handleSelectHistory}
      />
    </div>
  )
}
